{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c19b64b4-9023-4d48-9b47-983e243ee006",
   "metadata": {},
   "source": [
    "Chapter 22\n",
    "# 鸢尾花数据帧使用apply() 匿名lambda函数，对于特定两列\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "16df2645-8784-4173-bf0f-a0b787dc1d58",
   "metadata": {},
   "outputs": [],
   "source": [
    "import seaborn as sns\n",
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "440f31ad-6bc7-4c1b-9e66-e13a1d481afd",
   "metadata": {},
   "outputs": [],
   "source": [
    "iris_df = sns.load_dataset(\"iris\")\n",
    "# 从Seaborn中导入鸢尾花数据帧\n",
    "iris_df"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5c168ecb-56c6-4a6c-be4a-b97b42ac46b2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算鸢尾花各类花瓣平均宽度\n",
    "mean_X2_by_species = iris_df.groupby(\n",
    "    'species')['petal_width'].mean()\n",
    "mean_X2_by_species"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c35e1110-2a37-444c-8634-dc4ccd069f55",
   "metadata": {},
   "outputs": [],
   "source": [
    "    \n",
    "# 定义映射函数\n",
    "def map_petal_width(petal_width, species):\n",
    "    if petal_width > mean_X2_by_species[species]:\n",
    "        return \"YES\"\n",
    "    else:\n",
    "        return \"NO\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8724ce95-1a3d-4355-921e-b11dca5558dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 使用 map 方法将花瓣宽度映射为是否超过平均值\n",
    "iris_df['greater_than_mean'] = iris_df.apply(lambda \n",
    "       row: map_petal_width(row['petal_width'], \n",
    "                            row['species']), axis=1)\n",
    "iris_df"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
